#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
系统日志管理API - 使用统一日志系统
"""

from flask import request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from backend.models.system_log import SystemLog, SystemLogAction
from backend.models.user import User
from backend.infrastructure.database import db
from datetime import datetime, timedelta
from backend.api.user_api import admin_required
from backend.services.unified_log_service import log_service

@jwt_required()
@admin_required
def list_system_logs():
    """获取系统日志列表"""
    try:
        # 获取查询参数
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 50, type=int)
        action = request.args.get('action')
        target_id = request.args.get('target_id', type=int)
        start_date = request.args.get('start_date')
        end_date = request.args.get('end_date')
        
        # 构建查询
        query = SystemLog.query
        
        # 应用筛选条件
        if action:
            actions = [a.strip().upper() for a in action.split(',')]
            query = query.filter(SystemLog.action.in_(actions))
        
        if target_id:
            query = query.filter_by(target_id=target_id)
        
        if start_date:
            try:
                start_date_obj = datetime.strptime(start_date, '%Y-%m-%d')
                query = query.filter(SystemLog.operation_time >= start_date_obj)
            except ValueError:
                return jsonify({
                    'success': False, 
                    'message': '开始日期格式错误，应为YYYY-MM-DD',
                    'data': None
                }), 400
        
        if end_date:
            try:
                end_date_obj = datetime.strptime(end_date, '%Y-%m-%d') + timedelta(days=1)
                query = query.filter(SystemLog.operation_time < end_date_obj)
            except ValueError:
                return jsonify({
                    'success': False, 
                    'message': '结束日期格式错误，应为YYYY-MM-DD',
                    'data': None
                }), 400
        
        # 分页查询
        pagination = query.order_by(SystemLog.operation_time.desc()).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        # 获取用户信息
        user_ids = set()
        for log in pagination.items:
            if log.user_id:
                user_ids.add(log.user_id)
        
        users = {}
        if user_ids:
            user_list = User.query.filter(User.id.in_(user_ids)).all()
            users = {user.id: user.username for user in user_list}
        
        # 格式化日志数据
        logs_data = []
        for log in pagination.items:
            log_dict = log.to_dict()
            log_dict['username'] = users.get(log.user_id, '未知用户')
            logs_data.append(log_dict)
        
        return jsonify({
            'success': True,
            'data': logs_data,
            'pagination': {
                'page': page,
                'per_page': per_page,
                'total': pagination.total,
                'pages': pagination.pages,
                'has_next': pagination.has_next,
                'has_prev': pagination.has_prev
            },
            'filters': {
                'action': action,
                'target_id': target_id,
                'start_date': start_date,
                'end_date': end_date
            },
            'message': f'成功获取系统日志，共{pagination.total}条'
        }), 200
        
    except Exception as e:
        print(f"获取系统日志失败: {e}")
        return jsonify({
            'success': False,
            'message': f'获取系统日志失败: {str(e)}',
            'data': None
        }), 500

@jwt_required()
@admin_required
def get_system_log_detail(log_id):
    """获取系统日志详情"""
    try:
        log = SystemLog.query.get(log_id)
        if not log:
            return jsonify({
                'success': False,
                'message': '日志记录不存在',
                'data': None
            }), 404
        
        # 获取用户信息
        username = '未知用户'
        if log.user_id:
            user = User.query.get(log.user_id)
            if user:
                username = user.username
        
        log_dict = log.to_dict()
        log_dict['username'] = username
        
        return jsonify({
            'success': True,
            'data': log_dict,
            'message': '成功获取日志详情'
        }), 200
        
    except Exception as e:
        print(f"获取日志详情失败: {e}")
        return jsonify({
            'success': False,
            'message': f'获取日志详情失败: {str(e)}',
            'data': None
        }), 500

@jwt_required()
@admin_required
def get_system_log_stats():
    """获取系统日志统计信息"""
    try:
        # 获取最近7天的统计
        end_date = datetime.now()
        start_date = end_date - timedelta(days=7)
        
        # 按操作类型统计
        action_stats = db.session.query(
            SystemLog.action,
            db.func.count(SystemLog.id).label('count')
        ).filter(
            SystemLog.operation_time >= start_date
        ).group_by(SystemLog.action).all()
        
        action_data = []
        for action, count in action_stats:
            action_data.append({
                'action': action.value if action else 'UNKNOWN',
                'count': count
            })
        
        # 按用户统计
        user_stats = db.session.query(
            SystemLog.user_id,
            db.func.count(SystemLog.id).label('count')
        ).filter(
            SystemLog.operation_time >= start_date,
            SystemLog.user_id.isnot(None)
        ).group_by(SystemLog.user_id).order_by(
            db.func.count(SystemLog.id).desc()
        ).limit(10).all()
        
        user_data = []
        for user_id, count in user_stats:
            user = User.query.get(user_id)
            username = user.username if user else f'用户{user_id}'
            user_data.append({
                'user_id': user_id,
                'username': username,
                'count': count
            })
        
        return jsonify({
            'success': True,
            'data': {
                'action_stats': action_data,
                'user_stats': user_data,
                'period': {
                    'start_date': start_date.strftime('%Y-%m-%d'),
                    'end_date': end_date.strftime('%Y-%m-%d')
                }
            },
            'message': '成功获取日志统计信息'
        }), 200
        
    except Exception as e:
        print(f"获取日志统计失败: {e}")
        return jsonify({
            'success': False,
            'message': f'获取日志统计失败: {str(e)}',
            'data': None
        }), 500

@jwt_required()
@admin_required
def restore_system_log(log_id):
    """恢复系统日志记录"""
    try:
        # 获取当前用户信息
        current_user_id = get_jwt_identity()
        ip_address = request.remote_addr
        
        # 获取当前用户信息
        try:
            if current_user_id:
                current_user = User.query.get(int(current_user_id))
                operator = current_user.username if current_user else '未知用户'
            else:
                operator = '系统'
        except (ValueError, TypeError):
            operator = '未知用户'
        
        # 获取日志记录
        log = SystemLog.query.get(log_id)
        if not log:
            return jsonify({
                'success': False,
                'message': '日志记录不存在',
                'data': None
            }), 404
        
        # 检查日志类型
        if log.action == SystemLogAction.RESTORE:
            return jsonify({
                'success': False,
                'message': 'RESTORE日志是恢复操作的记录，不支持再次恢复',
                'data': None
            }), 400
        
        # 根据日志内容确定恢复的模型
        import json
        old_content = None
        if log.old_content:
            try:
                old_content = json.loads(log.old_content)
            except:
                old_content = log.old_content
        
        # 根据日志详情确定要恢复的模型
        # ✅ 修复：改进记录类型识别逻辑
        record_type = None
        
        # 方法1：通过日志详情中的关键字识别
        if log.detail:
            if '角色' in log.detail:
                record_type = 'role'
            elif '权限' in log.detail:
                record_type = 'permission'
            elif '用户' in log.detail:
                record_type = 'user'
        
        # 方法2：通过日志内容中的字段特征识别
        if not record_type and log.old_content:
            try:
                old_data = json.loads(log.old_content)
                if isinstance(old_data, dict):
                    # 角色特征：有name字段，没有username字段
                    if 'name' in old_data and 'username' not in old_data and 'code' not in old_data:
                        record_type = 'role'
                    # 权限特征：有code字段
                    elif 'code' in old_data:
                        record_type = 'permission'
                    # 用户特征：有username字段
                    elif 'username' in old_data:
                        record_type = 'user'
            except:
                pass
        
        # 方法3：通过日志内容中的字段特征识别
        if not record_type and log.new_content:
            try:
                new_data = json.loads(log.new_content)
                if isinstance(new_data, dict):
                    # 角色特征：有name字段，没有username字段
                    if 'name' in new_data and 'username' not in new_data and 'code' not in new_data:
                        record_type = 'role'
                    # 权限特征：有code字段
                    elif 'code' in new_data:
                        record_type = 'permission'
                    # 用户特征：有username字段
                    elif 'username' in new_data:
                        record_type = 'user'
            except:
                pass
        
        # 根据识别结果确定模型
        if record_type == 'role':
            from backend.models.role import Role as RecordModel
        elif record_type == 'permission':
            from backend.models.permission import Permission as RecordModel
        elif record_type == 'user':
            from backend.models.user import User as RecordModel
        else:
            return jsonify({
                'success': False,
                'message': '无法确定要恢复的记录类型',
                'data': None
            }), 400
        
        # 使用统一日志服务进行恢复
        result = log_service.restore_record(
            LogModel=SystemLog,
            RecordModel=RecordModel,
            log_id=log_id,
            operator=operator,
            ip_address=ip_address
        )
        
        if isinstance(result, tuple):
            return jsonify(result[0]), result[1]
        else:
            return jsonify(result), 200
            
    except Exception as e:
        print(f"恢复系统日志失败: {e}")
        return jsonify({
            'success': False,
            'message': f'恢复系统日志失败: {str(e)}',
            'data': None
        }), 500